// Time:  O(n)
// Space: O(1)

#include <vector>
#include <unordered_map>
using namespace std;

class Solution {
public:
    int totalFruit(vector<int>& fruits) {
        unordered_map<int, int> count;
        int result = 0;
        for (int i = 0, j = 0; j < fruits.size(); ++j) {
            ++count[fruits[j]];
            while (count.size() > 2) {
                --count[fruits[i]];
                if (count[fruits[i]] == 0) {
                    count.erase(fruits[i]);
                }
                ++i;
            }
            result = max(result, j - i + 1);
        }
        return result;
    }
};
